package worker

import (
	"go-crontab/common"
	"math/rand"
	"os/exec"
	"time"
)

// 执行器
type Excutor struct {
}

var (
	G_excutor *Excutor
)

func (excutor *Excutor) ExcutorJob(info *common.JobExcuteInfo) {
	go func() {
		var (
			cmd     *exec.Cmd
			err     error
			output  []byte
			result  *common.JobExcuteResult
			jobLock *JobLock
		)

		result = &common.JobExcuteResult{
			ExcuteInfo: info,
			Output:     make([]byte, 0),
		}

		jobLock = G_jobMgr.CreateJobLock(info.Job.Name)
		// 分布式master随机睡眠
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)

		// 加分布式锁
		err = jobLock.TryLock()
		defer jobLock.UnLock()

		result.StartTime = time.Now()
		if err != nil {
			result.Err = err
			result.EndTime = time.Now()
		} else { // 上锁成功
			// E:\\cygwin64\\bin\\bash.exe
			// /bin/bash
			cmd = exec.CommandContext(info.CancelCtx, "C:\\cygwin64\\bin\\bash.exe", "-c", info.Job.Command)
			output, err = cmd.CombinedOutput()

			result.Output = output
			result.Err = err
			result.EndTime = time.Now()
		}

		// 回传执行结果
		G_scheduler.PushJobResult(result)
	}()
}

func InitExcutor() (err error) {
	G_excutor = &Excutor{}
	return
}
